package com.common.base.utils

import android.content.Context
import android.os.CountDownTimer
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.common.base.R
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：14/2/2023
 *
 * 描述：倒计时
 *
 * 修订历史：
 *
 */
class MyTimeCountdown(
    millisInFuture: Long, countDownInterval: Long,
    mContext: Context, btn: TextView?
) : CountDownTimer(millisInFuture, countDownInterval) {
    private val mContext: Context
    private val btn: TextView?
    private var defaultPrompt: String? = null
    private var listener: OnMyTimeCountdownListener? = null
    private var tickColor = 0

    init {
        this.btn = btn
        this.mContext = mContext
    }

    constructor(
        millisInFuture: Long, countDownInterval: Long,
        mContext: Context, btn: TextView, defaultPrompt: String?
    ) : this(millisInFuture, countDownInterval, mContext, btn) {
        this.defaultPrompt = defaultPrompt
    }

    constructor(
        millisInFuture: Long, countDownInterval: Long,
        mContext: Context, btn: TextView, tickColor: Int
    ) : this(millisInFuture, countDownInterval, mContext, btn) {
        this.tickColor = tickColor
    }

    override fun onFinish() {
        btn?.setTextColor(ContextCompat.getColor(mContext, R.color.product_color))
        btn?.isEnabled = true
        //        btn.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_stroke_round_product7));
        btn?.isClickable = true

        defaultPrompt.isNullOrEmpty().no {
            btn?.text = defaultPrompt
        }.otherwise {
            btn?.setText(R.string.common_get_verification_code)
        }

        listener?.onTimeCountdownClick()
    }

    fun stop() {
        cancel()
        onFinish()
    }

    override fun onTick(millisUntilFinished: Long) {
        btn?.isClickable = false
        btn?.isEnabled = false
        if (tickColor != 0) {
            btn?.setTextColor(ContextCompat.getColor(mContext, tickColor))
        } else {
            btn?.setTextColor(ContextCompat.getColor(mContext, R.color.product_color))
        }

        btn?.text =  "${millisUntilFinished / 1000}S"
    }

    /**
     * 回调接口
     */
    interface OnMyTimeCountdownListener {
        fun onTimeCountdownClick()
    }

    /**
     * @param listener
     */
    fun setListener(listener: OnMyTimeCountdownListener?) {
        this.listener = listener
    }
}
